package com.zzyl.common.utils.deepseek;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

@Data
@AllArgsConstructor
public class ChatClient {
    private String baseUrl;
    private String apiKey;
    private String model;
    private String defaultSystem;


    public String chat(String prompt) {
        // 1.创建请求体对象
        ChatRequest request = ChatRequest.builder()
                .model(model)
                .messages(List.of(
                        Message.assistantMessage(defaultSystem),  // 改为 systemMessage
                        Message.userMessage(prompt)
                ))
                .stream(false)
                .build();

        // 2.调用DeepSeek
        HttpResponse response = HttpRequest.post(baseUrl)
                .bearerAuth(apiKey)
                .body(JSONUtil.toJsonStr(request)).execute();

        // 3.解析结果
        if (response.isOk()) {
            // 1.获取响应体
            String body = response.body();
            System.out.println("Success Response Body: " + body); // 打印响应体

            // 2.将响应体转为JSON对象
            JSONObject jsonObject = JSONUtil.parseObj(body);
            // 3.获取内容
            String content = jsonObject.getByPath("choices[0].message.content", String.class);
            return content;
        } else {
            // 打印错误响应
            System.err.println("Request failed with status: " + response.getStatus());
            System.err.println("Response body: " + response.body());

            // 可选：根据状态码返回更友好的提示
            switch (response.getStatus()) {
                case 401:
                    throw new RuntimeException("认证失败，请检查 API Key 是否正确");
                case 403:
                    throw new RuntimeException("权限不足，请确认模型访问权限");
                case 400:
                    throw new RuntimeException("请求参数错误：" + response.body());
                case 500:
                    throw new RuntimeException("服务器内部错误");
                default:
                    throw new RuntimeException("未知错误，状态码：" + response.getStatus());
            }
        }
    }

}